api = window.TS.api
app = window.TS.app

statusTranslate = (status)->
	switch status
		when "新建" then "todo"
		when "开发中" then "in-progress"
		when "开发完成" then "ready-for-test"
		when "解决" then "done"
		when "拒绝" then "refuse"
		when "反馈" then "feedback"

app.showTasks = ->
	api.get("/api/task").done (json)->
		if json
			$('.control .show-item').hide();
			$('.content.table').hide()
			$('.control .show').attr "class", "show show-block"
			$('.content.tasks').show()
			$(".tasks .task").remove()
			for data in json
				for key,val of data
					status = val if key is "status"
					id = val if key is "_id"
					name = val if key is "name"
					desc = val if key is "desc"
				status = statusTranslate status
				$task = $("<div>",
					class: "task"
					taskId: id
					html: "<div>#{name}</div><div>#{desc}</div>")
				.appendTo ".#{status} .task-content";
				$task.data "task", data
			$(".task").draggable({snap: true})

app.showTask = (relativeUrl, data)->
	$('#bcMark').show()
	api.getView(relativeUrl, data)
	.done((responseHTML, status)->
		$dialog = $(responseHTML)
		if data
			for key,val of data
				do (key) ->
					nodeName = if $dialog.find("[name=#{key}]")[0] then $dialog.find("[name=#{key}]")[0].nodeName else ""
					$dialog.find("[name=#{key}]").val(val)
					$dialog.find("[name=#{key}]").html(val) if nodeName.toLocaleLowerCase() isnt "select"
		else
			$dialog.find('[name=createTime]').val(api.formatDate())
			$dialog.find('[name=createTime]').html(api.formatDate())
			$dialog.find('[name=modifyTime]').val(api.formatDate())
			$dialog.find('[name=modifyTime]').html(api.formatDate())
		$dialog.appendTo("#taskDialog"))

app.showTable = ->
	api.get("/api/task").done (json)->
		listKey = ["_id"];
		$('.show-item .selected').each (i, e)->
			listKey.push $(this).attr "key"
		tBody = ""
		$tBody = $("<tbody>").appendTo $('.content.table table')
		for data in json
			$tr = $("<tr>").appendTo($tBody)
			$tr.data("task", data)
			$td = null
			for key,val of data
				if key in listKey
					$td = $("<td>", {
						key:key
						text:val
					})
				else
					$td = $("<td>", {
						key:key
						css:"display: none"
					})
				$td.appendTo $tr

#		$('.content.table table').find('tbody').html(tBody)

		$('.content.tasks').hide()
		$('.control .show').attr "class", "show show-table"
		$('.control .show-item').show();
		$('.content.table').show()
		$('.content.table tbody tr:first-child').click()

$('body')
.on "click", "*.main-nav li", ->
	$tab = $(this)
	$tab.addClass("active").siblings().removeClass("active")
	switch $tab.attr "name"
		when "show-tasks"
			app.showTasks()
		when "load-table"
			app.showTable()
		when "load-tasks"
			window.TS.router.navigate "tasks", false

# show a task
$('body')
.on "click", ".main-content .task", ->
	if $(this).hasClass 'selected'
		app.showTask "/page/taskDetails.html", $(this).data("task")
	else
		$('.main-content .task').removeClass 'selected'
		$(this).addClass 'selected'

# add a new task
$('body')
.on "click", ".add-task", ->
	app.showTask("/page/taskDetails.html")

# delete a new task
$('body')
.on "click", ".del-task", ->
	app.deleteTask()
	$(this).blur()

# close task
$('body')
.on "click", ".task-details .close", ->
	$('#bcMark').hide()
	$('#taskDialog').empty()

# save task
$('body')
.on "click", ".task-details .save", ->
	id = $('.task-details [name="_id"]').val() || 0;
	data =
		task: $('.task-details form').serializeObject()
	if id <= 0
		delete data.task._id
		app.addNewTask(data)
	else
		app.editTask id, data
	$('#bcMark').hide()
	$('#taskDialog').empty()
	app.showTasks()

app.addNewTask = (data)->
	api.post("/api/task/new", data).done ->
		modifyTaskHTML(0)

app.editTask = (id, data)->
	api.post("/api/task/new", data).done ->
		modifyTaskHTML(id)

app.deleteTask = ()->
	if $('.main-nav li[name="show-tasks"]').hasClass "active"
		if $('.tasks .selected').length > 0
			id = $('.tasks .selected').attr("taskId");
			api.delete("/api/task/delete/" + id).done ->
				$('.tasks .selected').remove()
		else
			alert "请选择要删除的问题"
	else
		if $('.table .selected').length > 0
			$('.table .selected').remove()
			$('.content.table tbody tr:first-child').click();
		else
			alert "请选择要删除的问题"

modifyTaskHTML = (id)->
	data = $('.task-details form').serializeObject()
	if $('.content.table').is(":hidden")
		for key,val of data
			status = val if key is "status"
			name = val if key is "name"
			desc = val if key is "desc"
		status = statusTranslate status
		html = "<div>#{name}</div><div>#{desc}</div>"
		if id > 0 #edit
			$("[taskId=#{id}]").html(html);
		else #add
			$('.tasks .selected').removeClass "selected"
			$("<div>", {
				class: "task selected"
				html: html
			}).appendTo($(".#{status} .task-content"));
	else
		td = ""
		listKey = [];
		$('.show-item .selected').each (i, e)->
			listKey.push $(this).attr "key"
		for key,val of data
			if key in listKey
				td += "<td key=#{key}>#{val}</td>"
			else
				td += "<td key=#{key} style='display: none;'>#{val}</td>"
		if id > 0 #edit
			$(".content.table tbody td:contains(#{id})").parent().html(td);
		else  #add
			$("<tr>#{td}</tr>").insertBefore($('.content.table tbody tr:first-child'))
			$('.content.table tbody tr:first-child').click();


$('body')
.on "click", ".main-content .control .show", ->
	if $(this).hasClass "show-block"
		$('.main-nav li[name="load-table"]').click()
	else
		$('.main-nav li[name="show-tasks"]').click()

$board = $(".tasks .task-content")

$board.droppable(
	out: (event, ui)->
		$(this).removeClass('open')
		data = $(ui.draggable[0]).data("task");
		app.showTask "/page/taskDetails.html", $(ui.draggable[0]).data("task")
)

$('.main-nav [name="show-tasks"]').click() # 默认显示task
